
package com.game.kugou.sdk;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.kugou.game.demo.R;
import com.kugou.game.sdk.api.common.KGPayInfo;
import com.kugou.game.sdk.api.common.OnExitListener;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.api.online.KGPlatform;

import java.util.UUID;

/**
 * 描述:demo界面，模拟登录前，登录后，进入游戏主界面这三个过程，演示调用SDK提供的常用api。
 *
 * @author kugou
 * @since 2015年7月8日 下午3:53:53
 */
public class MainActivity extends Activity implements OnClickListener {

    public static final String ACTION_LOGIN_SDK_SUCCESS = "com.kugou.platform.demo.ACTION_LOGIN_SDK_SUCCESS";

    private TextView mUserInfo, mTvEnv;

    private Button mBtnFixedRecharge, mBtnNormalRecharge, mBtnUserCenter, mBtnAppCenter,
            mBtnExitGame, mBtnLoginSDK, mBtnEnterGame;

    private LoginResultReceiver mReceiver;

    // 登录前，登录后，游戏主界面对应的三个视图
    private View mPageBeforeEnterGame, mPageAfterEnterGame, mPageGameActivity;

    private LocalBroadcastManager mLocalReceiverManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(KGPlatform.getSDKConfig().getActivityOrientation());
        setContentView(R.layout.demo_activity_main);
        initViews();
        // 注册登录SDK成功的广播
        initLoginSDKSuccessReceiver();
        // 设置显示未登录视图
        setViewState(STATE_BEFORE_ENTER_GAME);

        // 自动登录SDK
        KGPlatform.enterGame(this);
    }

    private void initViews() {
        mPageBeforeEnterGame = findViewById(R.id.demo_layout_before_enter_game);
        mPageAfterEnterGame = findViewById(R.id.demo_layout_after_enter_game);
        mPageGameActivity = findViewById(R.id.demo_layout_game_activity);

        mUserInfo = (TextView) findViewById(R.id.demo_tv_userinfo);
        mTvEnv = (TextView) findViewById(R.id.demo_tv_env_log);
        mTvEnv.setVisibility(KGPlatform.isOfficial() ? View.GONE : View.VISIBLE);
        mBtnLoginSDK = (Button) findViewById(R.id.demo_btn_enter_game);
        mBtnEnterGame = (Button) findViewById(R.id.demo_btn_start_game);
        mBtnFixedRecharge = (Button) findViewById(R.id.demo_btn_fixed_recharge);
        mBtnNormalRecharge = (Button) findViewById(R.id.demo_btn_normal_recharge);
        mBtnUserCenter = (Button) findViewById(R.id.demo_btn_usercenter);
        mBtnAppCenter = (Button) findViewById(R.id.demo_btn_appcenter);
        mBtnExitGame = (Button) findViewById(R.id.demo_btn_exit);

        mBtnLoginSDK.setOnClickListener(this);
        mBtnEnterGame.setOnClickListener(this);
        mBtnFixedRecharge.setOnClickListener(this);
        mBtnNormalRecharge.setOnClickListener(this);
        mBtnUserCenter.setOnClickListener(this);
        mBtnAppCenter.setOnClickListener(this);
        mBtnExitGame.setOnClickListener(this);
    }

    // 登录前
    private static final int STATE_BEFORE_ENTER_GAME = 1;

    // 登录后
    private static final int STATE_AFTER_ENTER_GAME = 2;

    // 进入游戏
    private static final int STATE_GAME_ACTIVITY = 3;

    private void setViewState(int state) {
        if (state == STATE_BEFORE_ENTER_GAME) {
            mPageBeforeEnterGame.setVisibility(View.VISIBLE);
            mPageAfterEnterGame.setVisibility(View.GONE);
            mPageGameActivity.setVisibility(View.GONE);
        } else if (state == STATE_AFTER_ENTER_GAME) {
            mPageBeforeEnterGame.setVisibility(View.GONE);
            mPageAfterEnterGame.setVisibility(View.VISIBLE);
            mPageGameActivity.setVisibility(View.GONE);
        } else if (state == STATE_GAME_ACTIVITY) {
            mPageBeforeEnterGame.setVisibility(View.GONE);
            mPageAfterEnterGame.setVisibility(View.GONE);
            mPageGameActivity.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 注册登录SDK成功广播接收器
     * 注意！！1、该广播不是SDK内部发出给游戏接收的！而是游戏收到SDK登录回调事件ENTER_GAME_SUCCESS发出通知界面的！
     * 2、登录成功后通过广播通知界面，这是demo采用的一种实现方式，不是SDK要求的固定实现方案，具体实现方案由游戏自行决定选择！
     */
    private void initLoginSDKSuccessReceiver() {
        mLocalReceiverManager = LocalBroadcastManager.getInstance(this);
        mReceiver = new LoginResultReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_LOGIN_SDK_SUCCESS);
        mLocalReceiverManager.registerReceiver(mReceiver, filter);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.demo_btn_enter_game) {
            // 登录SDK
            KGPlatform.enterGame(this);
        } else if (id == R.id.demo_btn_start_game) {
            // 显示进入游戏后的主界面
            setViewState(STATE_GAME_ACTIVITY);
            // 发送统计--进入游戏
            String roleName = "customRoleName";// 角色名称，默认填空字符串
            int roleLevel = 1; // 角色等级，默认填0
            int serverId = 1; // 区服ID
            KGPlatform.sendEnterGameStatics(roleName, roleLevel, serverId);

            // 当游戏等级发生变化时，务必记得通知SDK！
            // 例如：此处模拟游戏等级上升1级
            roleLevel++;
            KGPlatform.notifyGameInfoChanged(roleName, roleLevel);
        } else if (id == R.id.demo_btn_fixed_recharge) {
            KGPayInfo payInfo = new KGPayInfo();
            // 订单号，非空唯一且不能重复
            String orderId = UUID.randomUUID().toString();
            payInfo.setOrderId(orderId);
            // 区服id，如果没有则填默认值1
            payInfo.setServerId(1);
            // 游戏角色名
            payInfo.setRoleName("游戏角色名");
            // 扩展参数1
            payInfo.setExtension1("ext1");
            // 扩展参数2
            payInfo.setExtension2("ext2");
            // 进入【定额充值】中心(登录SDK后再调用)
            KGPlatform.enterRechargeCenter(this, payInfo, 1);
        } else if (id == R.id.demo_btn_normal_recharge) {
            KGPayInfo payInfo = new KGPayInfo();
            // 订单号，非空唯一且不能重复
            String orderId = UUID.randomUUID().toString();
            payInfo.setOrderId(orderId);
            // 区服id，如果没有则填默认值1
            payInfo.setServerId(1);
            // 游戏角色名
            payInfo.setRoleName("游戏角色名");
            // 扩展参数1
            payInfo.setExtension1("ext1");
            // 扩展参数2
            payInfo.setExtension2("ext2");
            // 进入【普通充值】中心(登录SDK后再调用)
            KGPlatform.enterRechargeCenter(this, payInfo);
        } else if (id == R.id.demo_btn_usercenter) {

            // 进入用户中心(登录SDK后再调用)
            KGPlatform.enterUserCenter(this);
        } else if (id == R.id.demo_btn_appcenter) {

            // 进入游戏中心(登录SDK后再调用)
            KGPlatform.enterGameCenter(MainActivity.this);
        } else if (id == R.id.demo_btn_exit) {
            // 退出游戏
            exitGame();
        }
    }

    /**
     * 退出游戏
     */
    private void exitGame() {
        String roleName = "customRoleName";// 角色名称，如果没有填空字符串
        int roleLevel = 1;// 角色等级，如果没有填0
        KGPlatform.exitGame(MainActivity.this, roleName, roleLevel, new OnExitListener() {
            @Override
            public void exitGame(int state) {
                // 做退出时没有礼包领取对话框的逻辑，在这里游戏调用退出逻辑，Demo用finish模拟
                finish();
                // 记得调用SDK的退出函数，释放资源
                KGPlatform.release(true);
            }

            @Override
            public void onDialogDismiss() {
                // 退出有礼包领取对话框显示时，对话框消失的回调
            }
        });
    }

    /**
     * SDK登录成功后的必选操作
     */
    private void doActionAfterLoginSuccess() {
        // 显示欢迎消息
        KGPlatform.showWelcomeDialog(this);

        // 显示悬浮窗
        KGPlatform.showToolBar(MainActivity.this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 销毁悬浮窗。注意：在界面被销毁前，必须执行该方法，建议在onDestroy()里执行
        KGPlatform.recycleToolBar(MainActivity.this);

        if (mReceiver != null) {
            mLocalReceiverManager.unregisterReceiver(mReceiver);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitGame();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 描述:登录SDK成功广播接收者
     *
     * @author kugou
     * @since 2015年7月8日 下午3:51:56
     */
    class LoginResultReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (MainActivity.ACTION_LOGIN_SDK_SUCCESS.equals(action)) {
                // 设置显示登录后视图
                setViewState(STATE_AFTER_ENTER_GAME);
                User user = KGPlatform.getCurrentUser();
                if (user != null) {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("1、openid(用户唯一标识)：" + user.getOpenId() + "\n");
                    stringBuilder.append("2、username：" + user.getAccountName() + "\n");
                    stringBuilder.append("3、nickname：" + user.getNickName() + "\n");
                    stringBuilder.append("4、token：" + user.getToken() + "\n");
                    stringBuilder.append("5、unixTime：" + user.getUnixTime() + "\n");
                    stringBuilder.append("6、bindPhoneNum：" + user.getBindPhoneNum() + "\n\n");

                    stringBuilder.append("SDK版本：" + KGPlatform.getVersionName() + "\n");

                    mUserInfo.setText(stringBuilder.toString());
                }

                // 执行登录成功后的非耗时操作
                doActionAfterLoginSuccess();
            }
        }
    }
}
